<template>
	<view class="content" :style="{ 'border-color': '' + defaultColor, 'background': bgDefaultColor }">
		<view
			v-for="(item, index) in switchArr"
			:key="index"
			class="switch_item"
			:class="{
				switch_selected: defaultValue == item.value ? true : false,
			}"
			@click="itemClick(item)"
			:style="{
				background: (defaultValue == item.value ? true : false) ? highColor : '',
			}"
		>
			<i v-if="switchType == 'icon'" class="uni-icon" :class="item.title"></i>
			<view
				v-if="switchType == 'text'"
				class="title"
				:style="{
					color: (defaultValue == item.value ? true : false) ? textColorActive : textColor,
				}"
				>{{ item.title }}</view
			>
		</view>
	</view>
</template>

<script>
export default {
	name: "YJYSwitch",
	props: {
		//默认选中的值，int类型
		defaultValue: {
			type: Number,
			default: 0,
		},
		//当前循环里的索引
		itemIndex: {
			type: Number,
			default: 0,
		},
		//选中的背景高亮颜色
		highColor: {
			type: String,
			default: "#FFFFFF",
		},
		//默认的背景颜色
		defaultColor: {
			type: String,
			default: "#fff",
		},
		//选中的文字颜色
		textColorActive: {
			type: String,
			default: "#262426",
		},
		//未选中的文字颜色
		textColor: {
			type: String,
			default: "#999799",
		},
		//组件边框背景色
		bgDefaultColor: {
			type: String,
			default: "#f3f2f3",
		},
		//类型，text：文本，icon：字体图标
		switchType: {
			type: String,
			default: "text",
		},
		//可用于切换的数组
		switchList: {
			type: Array,
			default: function () {
				return []
			},
		},
	},
	data() {
		return {
			//定义个组件内的数组
			switchArr: [],
		}
	},
	methods: {
		itemClick(swithcSelectItem) {
			if (this.defaultValue != swithcSelectItem.value) {
				this.$emit("switchFunction", { swithcSelectItem, ...{ index: this.itemIndex } })
			}
		},
	},
	created() {
		//初始化可选择的数据
		if (this.switchList.length > 0) {
			for (let i = 0; i < this.switchList.length; i++) {
				let arrItem = {
					title: this.switchList[i].title,
					value: this.switchList[i].value,
				}
				this.switchArr.push(arrItem)
			}
		}
	},
}
</script>

<style lang="scss" scoped>
.content {
	display: flex;
	flex-direction: row;
	border-radius: 50px;
	padding: 6rpx;

	.switch_selected {
		color: #ffffff;
		border-radius: 50px;
	}
	.switch_item {
		font-size: 14px;
		width: 50%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 0.4s ease-in-out;
	}
}
.title {
	font-size: 24rpx;
	padding: 10rpx 12rpx;
	margin-right: 4rpx;
	font-weight: 700;
}
</style>
